// 
// ExWidget.ts
// Author:qiuchun(362460803@qq.com)
// Time:2023.05.08 21:06:59
// Desc:Widget组件的扩展，实现背景图等比拉伸效果。
//

import { NodeEventType } from 'cc';
import { _decorator, Component, Node, Widget, log, UITransform, Sprite, error } from 'cc';
import { EDITOR } from 'cc/env';
const { ccclass, requireComponent, executeInEditMode, menu, property } = _decorator;



@ccclass('ExWidget')
@menu("UI/WidgetEX")
@requireComponent(UITransform)
@requireComponent(Sprite)
@executeInEditMode(true)
export class ExWidget extends Widget {

    onLoad() {

        this.node.on(NodeEventType.SIZE_CHANGED, this.changeSize, this);
    }

    onDestroy() {
        super.onDestroy();
        this.node.off(NodeEventType.SIZE_CHANGED, this.changeSize, this);
    }

    changeSize() {
        let sprite = this.node.getComponent(Sprite);
        if (sprite && sprite.spriteFrame) {
            let spriteFrame = sprite.spriteFrame;
            let width = spriteFrame.width;
            let height = spriteFrame.height;

            let uiTransform = this.node.getComponent(UITransform);
            if (uiTransform) {
                let sizeUI = uiTransform.contentSize;
                //等宽的时候，等比拉伸
                if (this.isStretchWidth && this.isStretchHeight == false) {
                    let newHeight = sizeUI.width * (height / width);
                    uiTransform.setContentSize(sizeUI.width, newHeight);
                }
                //登高的时候，等比拉伸
                else if (this.isStretchWidth == false && this.isStretchHeight) {
                    let newWidth = sizeUI.height * (width / height);
                    uiTransform.setContentSize(newWidth, sizeUI.height);
                }
            }
        }
    }
}


